﻿#include "additem.h"
#include "ui_additem.h"

AddItem::AddItem(QWidget *parent, int id) :
    QDialog(parent),
    ui(new Ui::AddItem)
{
    ui->setupUi(this);

    id_=id;
    table=P_CLIPBOARD;
    if(id_ != -1)   // 更新模式
    {
        setWindowTitle(QStringLiteral("更新条目"));
        ui->btn_submit->setText(QStringLiteral("保存"));
        ui->btn_submit->setAutoDefault(true);
    }
    else
        ui->btn_paste->setAutoDefault(true);
}

AddItem::~AddItem()
{
    delete ui;
}

void AddItem::setTopic(const QString &topic)
{
    ui->topic->setText(topic);
}

void AddItem::setItem(const QString &topic,
                      const QString &detail)
{
    topic_=topic;
    detail_=detail;

    ui->topic->setText(topic);
    ui->detail->setText(detail);
}

bool AddItem::addItem(const QString &topic,
                      const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (topic,detail) values (?,?)")
                  .arg(table));
    query.addBindValue(topic);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

bool AddItem::updateItem(const QString &topic,
                         const QString &detail)
{
    QSqlQuery query;
    QString sql=QString("update %1 set topic='%2',detail='%3' where id=%4")
            .arg(table)
            .arg(topic)
            .arg(detail)
            .arg(id_);
    if(query.exec(sql))
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddItem::on_btn_submit_clicked()
{
    QString topic=ui->topic->text().trimmed();
    if(topic.isEmpty())
        topic=DEF_TOPIC;

    QString detail=ui->detail->text().trimmed();
    if(detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    if(addItem(topic,detail))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}

void AddItem::on_btn_paste_clicked()
{
    QString text=qApp->clipboard()->text();
    if(!text.isEmpty())
        ui->detail->setText(text);
}

void AddItem::on_btn_clean_clicked()
{
    ui->detail->clear();
}
